/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.yynl.controller;

import com.dmgis.entity.DmMapRectangle;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.village;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.waterlogging_fcst;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.waterlogging_pointinfo;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CEntity;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CityFcstInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.LogQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.MyPoint;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.service.IConfigService;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.qxfw.dataservice.businessservice.yynl.service.IWarnQueryService;
import com.dmgis.qxfw.dataservice.gisservice.service.Transform;
import com.dmgis.weblib.MapCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * This class is used for 预警查询类
 *
 * @author dsq
 * @version 1.0, 2018年7月18日 下午3:33:27
 */
@Controller
@RequestMapping("/xtnl")
public class WarningQuery {
    private  final String operatingSystem;

    @Autowired
    public WarningQuery(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    @Resource
    IWarnQueryService warnQueryService;
    @Resource
    private IConfigService configService;
    @Resource
    private IQxInfoService qxInfoService;

    @Resource
    private ITransformService transformService;

    @Resource
    private Transform transform;

    MongoService1 ms = new MongoService1();


    @RequestMapping("/initLogQueryPage")
    @ResponseBody
    public Object initLogQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(warnQueryService.getLogNewDate());
        result.add(endDate.AddDays(-7).toDateString());
        result.add(endDate.toDateString());
        return result;
    }

    /**
     * 获取内涝预警信息
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年7月10日
     */
    @RequestMapping("/getLogInfo")
    @ResponseBody
    public Object getLogInfo(HttpServletRequest request, Model model) throws Exception {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        LogQuery logQuery = new LogQuery();
        logQuery.setStartDate(startDate + " 00:00:00");
        logQuery.setEndDate(DateTime.parseDateTime(endDate + " 23:59:59").toDateTimeString());
        List<LogWarning> result = warnQueryService.getLogInfo(logQuery);
        Map<Integer, WaterLoggingSet> colorMap = warnQueryService.getLogLevelInfo();

        // 兰伯特转经纬度
        for (LogWarning logWarning : result) {
            Double lon = 0.0;
            Double lat = 0.0;
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (logWarning.getWarnPos() != null) {
                String[] posArr = logWarning.getWarnPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        cEntity.setColor(strColor);
                        cEntity.setWarnLevel(colorMap.get(Integer.parseInt(strColor)).getGradeType());
                        String[] dotset = pos.split("#")[1].split(",");

                        Integer index = 0;
                        DmMapPoint[] points = new DmMapPoint[dotset.length];
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmMapPoint = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            MyPoint myPoint = new MyPoint(dmMapPoint.x, dmMapPoint.y);
                            tempPos.add(myPoint);
                            points[index] = new DmMapPoint(dmMapPoint.x, dmMapPoint.y);
                            index++;
                        }
                        DmMapRectangle rct = new DmMapRectangle();
                        MapCommon dmMapCom = new MapCommon();
                        int[] parts = new int[1];
                        parts[0] = points.length;
                        DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
                        lon += dmdotCenter.x;
                        lat += dmdotCenter.y;

                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);

                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                lon = lon / posArr.length;
                lat = lat / posArr.length;
                logWarning.setEntites(cEntities);
                Date date = logWarning.getForecastTime();
                logWarning.setDate(new DateTime(date).toDateString());
                logWarning.setForecastTime(null);
                logWarning.setLon(lon);
                logWarning.setLat(lat);
                // 文件处理
            }
        }
        return result;
    }

    @RequestMapping("/showDoc")
    @ResponseBody
    public String showDoc(HttpServletRequest request, Model model) {
        String servicePath = "";
        String docPath = request.getParameter("docpath");
        if (docPath == null || docPath.equals("")) {
            return "";
        }
        String id = warnQueryService.getProductID(docPath);// 获取编号
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "\\Temp\\logWarning\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "\\Temp\\logWarning\\";// 临时文件目录
        }

        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docPath.split("\\\\")[docPath.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "\\Temp\\logWarning\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "/Temp/logWarning/" + fileName.replace(doctype, "pdf");
                }

                servicePath = basePath+servicePath;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                FileUtil.bytesToFile(data, pdfPath);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                if (operatingSystem.equals("Windows")){
                    servicePath = "\\Temp\\logWarning\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "/Temp/logWarning/" + fileName.replace(doctype, "pdf");
                }
                servicePath = basePath+servicePath;
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /**
     * 获取内涝点信息
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月19日
     */
    @RequestMapping("/showPoint")
    @ResponseBody
    public Object showPoint(HttpServletRequest request, Model model) {
        try {
            int docId = Integer.parseInt(request.getParameter("id"));
            List<WaterLogPoint> logPoints = warnQueryService.getLogPointInfo(docId);
            return logPoints;
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }

    /* 易涝点 */
    @RequestMapping("/getwaterlogpnt")
    @ResponseBody
    public Object getwaterlogpnt(HttpServletRequest request, Model model) {
        List<waterlogging_pointinfo> logPoints = warnQueryService.getwaterlogpnt();
        return logPoints;
    }

    /**
     * 获取气象台发布的预警信号
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月19日
     */
    @RequestMapping("/showWarning")
    @ResponseBody
    public Object showWarning(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        return warnQueryService.getWarningInfo(startDate, endDate, -1);// 查询时间段内的预警信息号
    }

    /* 预警区内实况信息 */
    @RequestMapping("/getSKinfo")
    @ResponseBody
    public Object getSKinfo(HttpServletRequest request, Model model) throws Exception {
        String startDate = request.getParameter("startDate") + " 00:00:00";// 开始时间
        String endDate = request.getParameter("endDate") + " 23:59:59";// 结束时间
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<DmMapPoint> lonlat = new ArrayList<DmMapPoint>();
        List<String> stationids = new ArrayList<String>();
        String skstations = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                DmMapPoint[] point = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    points[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    point[index] = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    index++;
                }
                MapCommon dmMapCom = new MapCommon();
                int[] parts = new int[1];
                parts[0] = points.length;
                DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(points));
                DmMapPoint dmDotLb1 = new DmMapPoint(rect.minX, rect.minY);
                DmMapPoint dmDotLb2 = new DmMapPoint(rect.maxX, rect.maxY);
                rect.minX = dmDotLb1.x;
                rect.minY = dmDotLb1.y;
                rect.maxX = dmDotLb2.x;
                rect.maxY = dmDotLb2.y;
                List<smallscale_station> stations = qxInfoService.getStations(rect);
                for (smallscale_station city : stations) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLongitude(), city.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    if(dmMapCom.pointWithinPolygon(Arrays.asList(point),dmDotLb.x,dmDotLb.y)){
                        if (!skstations.contains(city.getStationid())) {
                            skstations += city.getStationid() + ",";
                            lonlat.add(dmDotJW);
                            stationids.add(city.getStationid());
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<MediumSmallScale> resultList = new ArrayList<MediumSmallScale>();
        List<msgmediumsmallscale> dataList = new ArrayList<>();
        if (stationids.size() > 0) {
            dataList = qxInfoService.getSKinfo(startDate, endDate, stationids);
        }
        for (msgmediumsmallscale msg : dataList) {
            MediumSmallScale smallscale = new MediumSmallScale();
            smallscale.setObservTime(msg.getObservtime());
            smallscale.setStationID(msg.getStationid());
            smallscale.setLongitude(msg.getLongitude());
            smallscale.setLatitude(msg.getLatitude());
            smallscale.setLon(msg.getLongitude());
            smallscale.setLat(msg.getLatitude());
            smallscale.setStationName(msg.getStationname());
            smallscale.setRain(Float.parseFloat(String.format("%.1f", msg.getRain())));
            smallscale.setDryBulbTemp(Float.parseFloat(String.format("%.1f", msg.getDrybulbtemp())));
            smallscale.setInstantWindV(Float.parseFloat(String.format("%.1f", msg.getInstantwindv())));
            smallscale.setRelHumidity(msg.getRelhumidity());
            smallscale.setPressureSea(Float.parseFloat(String.format("%.1f", msg.getStationpress())));
            smallscale.setCity(msg.getCity());
            smallscale.setCounty(msg.getCounty());
            DmMapPoint Dt = new DmMapPoint(msg.getLongitude(), msg.getLatitude());
            DmMapPoint ltDot = transformService.LonLatConvertToLambert(Dt.x, Dt.y);
            smallscale.setX(ltDot.x);
            smallscale.setY(ltDot.y);
            resultList.add(smallscale);
        }
        return resultList;
    }

    /* 预警区内预报信息 */
    @RequestMapping("/getYBinfo")
    @ResponseBody
    public Object getYBinfo(HttpServletRequest request, Model model) throws Exception {
        String poss = request.getParameter("pos");// 坐标
        String[] posArr = poss.split("\\*");// 三个部分，*分隔
        List<DmMapPoint> lonlat = new ArrayList<DmMapPoint>();
        List<String> stationids = new ArrayList<String>();
        String ybstations = "";
        for (String pos : posArr) {
            try {
                if (pos == null || pos.equals("")) {
                    continue;
                }
                String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                DmMapPoint[] point = new DmMapPoint[dotset.length];
                DmMapPoint[] points = new DmMapPoint[dotset.length];
                Integer index = 0;
                for (String strDot : dotset) {
                    String[] dot = strDot.split(" ");
                    points[index] = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    point[index] = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                    index++;
                }
                MapCommon dmMapCom = new MapCommon();
                int[] parts = new int[1];
                parts[0] = point.length;
                DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(point));
                DmMapPoint dmDotLb1 = transformService.LambertConvertToLonLat(rect.minX, rect.minY);
                DmMapPoint dmDotLb2 = transformService.LambertConvertToLonLat(rect.maxX, rect.maxY);
                rect.minX = dmDotLb1.x;
                rect.minY = dmDotLb1.y;
                rect.maxX = dmDotLb2.x;
                rect.maxY = dmDotLb2.y;
                List<township_station> stations = qxInfoService.getYBStations(rect);
                for (township_station city : stations) {
                    DmMapPoint dmDotJW = new DmMapPoint(city.getLongitude(), city.getLatitude());
                    DmMapPoint dmDotLb = transformService.LonLatConvertToLambert(dmDotJW.x, dmDotJW.y);
                    if (dmMapCom.pointWithinPolygon(Arrays.asList(points), dmDotLb.x, dmDotLb.y)) {
                        if (!ybstations.contains(city.getStationid())) {
                            ybstations += city.getStationid() + ",";
                            lonlat.add(dmDotJW);
                            stationids.add(city.getStationid());
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
        }
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        List<township_forecasttemp> fcstList = new ArrayList<township_forecasttemp>();
        if (stationids.size() > 0) {
            fcstList = qxInfoService.getYBinfo(stationids);
        }
        int count = fcstList.toArray().length;
        if (count > 0) {
            WebCtrlData wcd = new WebCtrlData();
            for (int i = 0; i < count; i += 2) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                if (strCountyName.contains("乡")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                }
                if (strCountyName.contains("镇")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindd().toString().replace("-65535", "0").trim());
                String windV12 =  wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWinds())));
                String windV24 =  wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWinds())));
                String windS12 = String.valueOf(fcstList.get(i).getWinds());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWinds());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12 ;
                } else {
                    windV += windV12 + "~" + windV24 ;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转" + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i).getMaxtemp() > fcstList.get(i + 1).getMaxtemp()
                        ? fcstList.get(i).getMaxtemp() : fcstList.get(i + 1).getMaxtemp();
                double minTemp = fcstList.get(i).getMintemp() > fcstList.get(i + 1).getMintemp()
                        ? fcstList.get(i + 1).getMintemp() : fcstList.get(i).getMintemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        }
        return resultList;
    }

    /* 地理分析 */
    @RequestMapping("/getAnalysis")
    @ResponseBody
    public Object getAnalysis(HttpServletRequest request, Model model) throws Exception {
        String analysis = request.getParameter("analysis");// 分析图层
        String result = "[";
        if (analysis.contains("内涝点")) {
            String poss = request.getParameter("pos");// 坐标
            String[] posArr = poss.split("\\*");// 三个部分，*分隔
            String waternames = "";
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint Dt = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = Dt;
                        index++;
                    }
                    List<waterlogging_pointinfo> resultList = warnQueryService.getwaterlogpnt();
                    for (waterlogging_pointinfo city : resultList) {
                        DmMapPoint dmDotJW = new DmMapPoint(city.getLon(), city.getLat());
                        MapCommon dmMapCom = new MapCommon();
                        if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotJW.x,dmDotJW.y)){
                            if (!waternames.contains(city.getName())) {
                                waternames += city.getName() + ",";
                                result += "{";
                                result += "\"name\":\"" + city.getName() + "\",";
                                result += "\"waterwarningvalue\":\"" + city.getWaterwarningvalue() + "\",";
                                result += "\"county\":\"" + city.getCounty() + "\",";
                                result += "\"waterreason\":\"" + city.getWaterreason() + "\",";
                                result += "\"waterdepth\":\"" + city.getWaterdepth() + "\",";
                                result += "\"waterarea\":\"" + city.getWaterarea() + "\",";
                                result += "\"principal\":\"" + city.getPrincipal() + "\",";
                                result += "\"tel\":\"" + city.getTel() + "\",";
                                result += "\"lon\":" + city.getLon() + ",";
                                result += "\"lat\":" + city.getLat() + "";
                                result += "},";
                            }
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }

        } else if (analysis.contains("村点")) {
            String poss = request.getParameter("pos");// 坐标
            String[] posArr = poss.split("\\*");// 三个部分，*分隔
            String villagenames = "";
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    String[] dotset = pos.split("#")[1].split(",");// 坐标数组
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    Integer index = 0;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        DmMapPoint Dt = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = Dt;
                        index++;
                    }
                    MapCommon dmMapCom = new MapCommon();
                    int[] parts = new int[1];
                    parts[0] = points.length;
                    DmMapRectangle rect = dmMapCom.getObjRect(Arrays.asList(points));
                    DmMapPoint dmDotLb1 = new DmMapPoint(rect.minX, rect.minY);
                    DmMapPoint dmDotLb2 = new DmMapPoint(rect.maxX, rect.maxY);
                    rect.minX = dmDotLb1.x;
                    rect.minY = dmDotLb1.y;
                    rect.maxX = dmDotLb2.x;
                    rect.maxY = dmDotLb2.y;
                    List<village> resultList = qxInfoService.getCountryPoint(rect);
                    for (village city : resultList) {
                        DmMapPoint dmDotJW = new DmMapPoint(city.getLon(), city.getLat());
                        if(dmMapCom.pointWithinPolygon(Arrays.asList(points),dmDotJW.x,dmDotJW.y)){
                            if (!villagenames.contains(city.getVillagename())) {
                                villagenames += city.getVillagename() + ",";
                                result += "{";
                                result += "\"dmgisId\":\"" + city.getId() + "\",";
                                result += "\"stationName\":\"" + city.getVillagename() + "\",";
                                result += "\"population\":\"" + city.getPopulation() + "\",";
                                result += "\"mayor\":\"" + city.getVillagehead() + "\",";
                                result += "\"tel\":\"" + city.getContacttel() + "\",";
                                result += "\"lon\":" + city.getLon() + ",";
                                result += "\"lat\":" + city.getLat() + ",";
                                result += "\"county\":\"" + city.getCountry() + "\"";
                                result += "},";
                            }
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
        }
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        result = result + "]";
        return result;
    }

    /* 得到内涝预警文档描述 */
    @RequestMapping("/getNLWarning")
    @ResponseBody
    public Object getSLWarning(HttpServletRequest request, Model model) throws Exception {
        List<waterlogging_fcst> resultList = warnQueryService.getNLWarning(); //
        if(resultList.size()==0){
            return null;
        }else {
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            resultList.get(0).setTime(simpleDateFormat.format(resultList.get(0).getForecasttime()));
            return resultList;
        }

    }


    /**
     * 初始化内涝逐小时产品时间
     *
     * @param
     * @return
     * @author
     * @date 2019/12/25
     **/
    @RequestMapping("/InitNltime")
    @ResponseBody
    public Object InitNltime() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(warnQueryService.InitNltime());
        result.add(endDate.AddHours(-6).toDateTimeString());
        result.add(endDate.toDateTimeString());
        return result;
    }



    /**
     * 获取逐小时图片
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showHourImg")
    @ResponseBody
    public Object showHourImg(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<base_product> base_products = warnQueryService.showHourImg(startDate, endDate);
        List<String> result = new ArrayList<String>();
        String servicePath = "";// 服务器文件
        for(base_product product : base_products){
            String id = product.getId().toString();// 获取编号
            String urlpath ;
            if (operatingSystem.equals("Windows")){
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Hourlyproduct\\";// 临时文件目录
            }else {
                 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Hourlyproduct/";// 临时文件目录
            }

            String path = request.getContextPath();
            String basePath = DbConfig.IP + path;
            FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
            FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
            String fileName = product.getProductname();// 文件名
            String file = fileName.split("[.]")[0] + ".JPG";
            servicePath = urlpath + file;// 服务器路径
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "\\Temp\\Hourlyproduct\\" + file;
                }else {
                    servicePath = "/Temp/Hourlyproduct/" + file;
                }

                servicePath = basePath+servicePath;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "image_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, servicePath);
                if (operatingSystem.equals("Windows")){
                    servicePath = "\\Temp\\Hourlyproduct\\" + file;
                }else {
                    servicePath = "/Temp/Hourlyproduct/" + file;
                }

                servicePath = basePath+servicePath;
            }
            servicePath = servicePath.replace("\\", "/");
            result.add(servicePath);
        }
        return result;
    }



    @RequestMapping("/GetCatchmentarea")
    @ResponseBody
    public Object GetCatchmentarea(HttpServletRequest request, Model model) throws Exception {
        List<SysConfig> result = warnQueryService.GetCatchmentarea();
        // 兰伯特转经纬度
        for (SysConfig dzWarning : result) {
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getParamValue())) {
                String[] posArr = dzWarning.getParamValue().split("\\*");

                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor ="#9DCDE3";
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint Dt = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(Dt.x, Dt.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setParamValue(dzWarning.getParamValue());
                dzWarning.setEntites(cEntities);
            }


        }
        return result;
    }



}

/**
 * This class is used for 面实体排序
 *
 * @author dsq
 * @version 1.0, 2018年7月14日 下午4:42:35
 */
class SortByColor implements Comparator<Object> {
    public int compare(Object o1, Object o2) {
        CEntity entity1 = (CEntity) o1;
        CEntity entity2 = (CEntity) o2;
        if (Integer.parseInt(entity1.getColor()) > Integer.parseInt(entity2.getColor()))
            return 1;
        return -1;
    }
}